package cn.maka.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
    private List<String> list = new ArrayList<String>();

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
       // HttpServletRequest request = (HttpServletRequest) req;

        ServletRequest pro_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("getParameter".equals(method.getName())) {

                    String value = (String) method.invoke(req,args);

                    if (value!=null){
                        for (String s : list) {
                            if (value.contains(s)){
                                value = value.replaceAll(s, "***");
                            }
                        }

                        /*for (int i = 0; i < list.size(); i++) {
                            System.out.println(list.get(i));

                            if (value.contains(list.get(i))){
                                value = value.replaceAll(list.get(i), "***");
                            }
                        }*/
                    }

                    return value;

                } else {
                    return method.invoke(req,args);
                }


            }
        });

        chain.doFilter(pro_req, resp);


    }

    public void init(FilterConfig config) throws ServletException {
        try{

            ServletContext servletContext = config.getServletContext();
            String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感词汇.txt");

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(realPath), "GBK"));

            String line = null;

            while ((line = bufferedReader.readLine()) != null){
                list.add(line);
            }

            bufferedReader.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
